<template>
	<view class="category-navbar">
		<scroll-view class="scroll-view-wrapper" scroll-x="true" :show-scrollbar="false">
			<view class="category-list">
				<view
					v-for="category in categories"
					:key="category"
					:class="['category-item', { 'active': selectedCategory === category }]"
					@click="selectCategory(category);cout(category)"
				>
					{{ category }}
				</view>
			</view>
		</scroll-view>
	</view>

	<view class="home-page">
		<!-- Existing content starts here -->
		<view class="post-card" v-for="i in list" :key="i.posts.id">
			<!-- 用户信息和内容 -->
			<view class="post-header">
				<text class="username">{{i.username}}</text>
			</view>
			<view class="post-content">
				<text class="content-text">
					{{i.posts.content}}
				</text>
			</view>

			<!-- 互动数据 -->
			<view class="post-actions">
				<text class="action-item">{{i.posts.like_count }}赞</text>
				<text class="action-item comment-toggle" @click="toggleCommentsSection(i.posts.post_id)">{{i.posts.comment_count}}评论</text>
				<text class="action-item">{{i.posts.share_count}}分享</text>
				<text class="post-source">#{{i.tags.tag_name}}#</text>
				<text class="post-date">{{i.posts.timestamp}}</text>
				<text class="post-source">{{i.posts.platform}}</text>
			</view>

			<!-- 评论区 -->
			<view class="comments-section" v-if="postCommentsVisibility[i.posts.post_id]">
				<view class="comment-input-area">
					<input
						class="comment-input"
						v-model="newCommentInput[i.posts.post_id]"
						placeholder="发表你的评论..."
						@confirm="addComment(i.posts.post_id)"
					/>
					<button class="send-button" @click="addComment(i.posts.post_id)">发送</button>
				</view>
				<view v-if="listc.length > 0" class="comment-list">
					<view v-for="comment in listc"  class="comment-item">
						<text class="comment-user">{{ comment.username }}</text>
						<text class="comment-content">{{ comment.comments.content }}</text>
						<text class="comment-date">{{ comment.comments.timestamp }}</text>
					</view>
				</view>
				<view v-else class="no-comments">
					暂无评论，快来发表第一条评论吧！
				</view>
			</view>
		</view>
	</view>
	<view class="pagination-section">
		<button class="pagination-button"  @click="up">上一页</button>
		<text class="pagination-info">第{{ page }}页，共{{ totalPages }}页</text>
		<button class="pagination-button"  @click="next">下一页</button>
	</view>
</template>

<script setup>
	import {
		onMounted,
		reactive,
		ref
	} from 'vue';

	const categories = ref([
		// '推荐', // 可以添加一个“推荐”或“全部”分类
		'热搜',
		'健身',
		'娱乐',
		'微博',
		'旅行',
		'明星',
		
		'生活',
		'社会',
		'美食',
		'话题'
	]);
	const selectedCategory = ref('热搜'); // 默认选中“推荐”分类
	const page = ref(1);
	const list = reactive([]);
	const listc = reactive([]);
	const totalPages = ref(0);


	// 获取总条目数
	const cout = (category) => {
		uni.request({
			url: "http://localhost:8080/count", // 修正 URL
			data:{
				tag_name: category
			}, // Fixed: Added missing comma here
			success: (res) => {
				totalPages.value = res.data;
			},
			fail: (err) => {
				console.error("获取总数失败:", err);
				uni.showToast({ title: '获取总数失败', icon: 'none' });
			}
		});
	};

	// 获取数据
	const data = (category) => {
		uni.request({
			url: "http://localhost:8080/dat", // 修正 URL
			data: {
				page: page.value,
				tag_name: category // Pass the selected category to the backend
			},
			success: (res) => {
				list.splice(0); // 清空现有列表
				const da = res.data;
				for (let i = 0; i < da.length; i++) {
					list.push(da[i]);
				}
				
			},
			fail: (err) => {
				console.error("获取数据失败:", err);
				uni.showToast({ title: '获取数据失败', icon: 'none' });
			}
		});
	};

	// 下一页
	const next = () => {
		if (page.value < totalPages.value) {
			page.value++;
			console.log(page.value);
			data(selectedCategory.value);
		} else {
			uni.showToast({ title: '已经是最后一页了', icon: 'none' });
		}
	};

	// 上一页
	const up = () => {
		if (page.value > 1) {
			page.value--;
			data(selectedCategory.value);
		} else {
			uni.showToast({ title: '已经是第一页了', icon: 'none' });
		}
	};

	// 选择分类
	const selectCategory = (category) => {
		selectedCategory.value = category;
		page.value = 1; // 切换分类时重置到第一页
		data(category); // 重新加载数据
	};

	// 页面加载时执行
	onMounted(() => {
		cout(selectedCategory.value); // 先获取总数
		data(selectedCategory.value); // 再获取初始数据
	});

	// 评论区相关变量和函数
	const postCommentsVisibility = reactive({}); // { postId: boolean }
	const postCommentsData = reactive({});     // { postId: [{ id, user, text, timestamp }] }
	const newCommentInput = reactive({});      // { postId: string } for the input field per post

	const fetchComments = (postId) => {
		uni.request({
			url: `http://localhost:8080/coms?post_id=${postId}`, // 假设评论接口
			success: (res) => {
				listc.splice(0); // 清空现有列表
				let da = res.data;
				for (let i = 0; i < da.length; i++) {
					listc.push(da[i]);
				}
			},
			fail: (err) => {
				console.error("获取评论失败:", err);
				uni.showToast({ title: '获取评论失败', icon: 'none' });
				postCommentsData[postId] = []; // Ensure it's an empty array on failure
			}
		});
	};

	const toggleCommentsSection = (postId) => {
		// Initialize visibility if not set
		if (postCommentsVisibility[postId] === undefined) {
			postCommentsVisibility[postId] = false;
		}
		// Toggle visibility
		postCommentsVisibility[postId] = !postCommentsVisibility[postId];

		// If comments section is now visible and comments for this post haven't been loaded yet, fetch them
		if (postCommentsVisibility[postId] && (!postCommentsData[postId] || postCommentsData[postId].length === 0)) {
			fetchComments(postId);
		}
	};

	const addComment = (postId) => {
		const commentText = newCommentInput[postId] ? newCommentInput[postId].trim() : '';
		if (commentText) {
			// Simulate sending comment to backend
			uni.request({
				url: `http://localhost:8080/coms`, // 假设添加评论接口
				method: 'POST',
				data: {
					postId: postId,
					content: commentText, // Use 'content' as per backend expectation
					username: '我' // Simulate current user
				},
				success: (res) => {
					newCommentInput[postId] = ''; // Clear input
					uni.showToast({
						title: '评论成功',
						icon: 'success',
						duration: 1000
					});
					// Re-fetch comments to update the list with the newly added comment from the server
					fetchComments(postId);
				},
				fail: (err) => {
					console.error("发表评论失败:", err);
					uni.showToast({
						title: '发表评论失败',
						icon: 'none',
						duration: 1000
					});
				}
			});
		} else {
			uni.showToast({
				title: '评论内容不能为空',
				icon: 'none',
				duration: 1000
			});
		}
	};
// onload(options) {
//   if (options.token) {
//     // 解码token参数
//     const token = decodeURIComponent(options.token);
    
//     // 示例：将token存储到组件数据中
//     this.token = token;
    
//     // 或者执行其他操作，如验证token等
//     this.verifyToken(token);
//   };
// };
</script>

<style scoped>
.category-navbar {
	position: sticky;
	top: 0;
	z-index: 100;
	background-color: #ffffff; /* Keep white as requested */
	box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
	padding: 20rpx 0;
	white-space: nowrap; /* Ensure items stay in one line for scroll-x */
}

.scroll-view-wrapper {
	width: 100%;
	height: 80rpx; /* Adjust height as needed */
}

.category-list {
	display: flex;
	padding: 0 20rpx;
	align-items: center;
	height: 100%;
}

.category-item {
	display: inline-flex; /* Use inline-flex for items within scroll-x */
	align-items: center;
	justify-content: center;
	padding: 10rpx 25rpx;
	margin-right: 20rpx;
	border-radius: 40rpx;
	font-size: 30rpx;
	color: #666666; /* Medium grey for inactive text */
	background-color: #e0f7fa; /* Very light cyan for inactive items */
	transition: all 0.2s ease;
	flex-shrink: 0; /* Prevent items from shrinking */
}

.category-item.active {
	background-color: #5cdbd3; /* Light green for active item background */
	color: #ffffff; /* White for active item text */
	font-weight: bold;
}

.home-page {
	background-color: #f0f9ff; /* Light grey-blue for overall background */
	min-height: 100vh;
	padding: 20rpx;
	box-sizing: border-box;
}

.post-card {
	background-color: #ffffff; /* White background */
	border-radius: 24rpx; /* Increased border-radius for more rounded corners */
	box-shadow: 0 8rpx 20rpx rgba(0, 0, 0, 0.05); /* Softer shadow */
	padding: 30rpx;
	margin-bottom: 30rpx;
}

.post-header {
	margin-bottom: 20rpx;
}

.username {
	font-size: 36rpx;
	font-weight: bold;
	color: #333333; /* Dark grey for username */
}

.post-content {
	margin-bottom: 20rpx;
}

.content-text {
	font-size: 32rpx;
	line-height: 1.5;
	color: #333333; /* Dark grey for content text */
}

.post-actions {
	display: flex;
	align-items: center;
	flex-wrap: wrap;
	font-size: 28rpx;
	color: #666666; /* Medium grey for action items */
	margin-top: 20rpx;
	border-top: 1rpx solid #eeeeee; /* Light grey border */
	padding-top: 20rpx;
}

.action-item {
	margin-right: 30rpx;
}

.comment-toggle {
	color: #5cdbd3; /* Light green for comment text to indicate clickability */
	text-decoration: none; /* Remove underline for cleaner look */
}

.post-date {
	margin-left: auto;
	margin-right: 20rpx;
}

.post-source {
	color: #999999; /* Lighter grey for source */
}

.comments-section {
	margin-top: 30rpx;
	border-top: 1rpx solid #eeeeee; /* Light grey border */
	padding-top: 20rpx;
}

.comment-input-area {
	display: flex;
	margin-bottom: 20rpx;
}

.comment-input {
	flex: 1;
	height: 70rpx;
	border: 2rpx solid #b5f5ec; /* Lighter green border for input */
	border-radius: 35rpx; /* Rounded input box */
	padding: 0 25rpx;
	font-size: 28rpx;
	color: #333333;
	margin-right: 15rpx;
	box-sizing: border-box;
}

.send-button {
	width: 120rpx;
	height: 70rpx;
	background-color: #5cdbd3; /* Light green for send button */
	color: #ffffff; /* White text */
	font-size: 28rpx;
	border-radius: 35rpx;
	display: flex;
	justify-content: center;
	align-items: center;
}

.comment-list {
	display: flex;
	flex-direction: column;
	gap: 15rpx;
}

.comment-item {
	background-color: #f5faff; /* Slightly different light grey-blue for comment items */
	border-radius: 10rpx;
	padding: 15rpx 20rpx;
	font-size: 28rpx;
	color: #333333;
	display: flex;
	flex-direction: column;
	gap: 5rpx;
}

.comment-user {
	font-weight: bold;
	color: #555555;
}

.comment-content {
	/* No specific styles needed unless different from default text */
}

.comment-date {
	font-size: 24rpx;
	color: #999999;
	margin-top: 5rpx;
}

.no-comments {
	text-align: center;
	color: #999999;
	font-size: 28rpx;
	padding: 20rpx 0;
}

.pagination-section {
	display: flex;
	justify-content: center;
	align-items: center;
	padding: 30rpx 0;
	background-color: #ffffff;
	border-top: 1rpx solid #eeeeee;
	margin-top: 30rpx;
}

.pagination-button {
	background-color: #5cdbd3; /* Light green for pagination buttons */
	color: #ffffff; /* White text */
	font-size: 28rpx;
	padding: 15rpx 30rpx;
	border-radius: 35rpx; /* Rounded corners for pagination buttons */
	margin: 0 20rpx;
	min-width: 180rpx;
	text-align: center;
}

.pagination-info {
	font-size: 28rpx;
	color: #666666;
}
</style>